import log from '../logger'
import { aliCloudConfigManager, AliCloudVoiceConfig } from '../utils/AliCloudConfigManager'

// 保持向后兼容的接口定义
export interface AliCloudVoiceConfigLegacy {
  accessKeyId: string
  accessKeySecret: string
  endpoint?: string
}

export interface VoiceCallParams {
  phoneNumber: string
  ttsCode: string
  calledShowNumber?: string
  playTimes?: number
}

export interface VoiceCallResult {
  success: boolean
  callId?: string
  requestId?: string
  code?: string
  message?: string
  error?: string
}

export class AliCloudVoiceService {
  private config: AliCloudVoiceConfig | null = null
  private client: any
  private clientInitialized = false

  constructor(config?: AliCloudVoiceConfig) {
    if (config) {
      // 使用传入的配置（向后兼容）
      this.config = config
    } else {
      // 从配置文件加载
      this.loadConfigFromFile()
    }
    
    // 初始化将在需要时异步进行
  }

  private loadConfigFromFile(): boolean {
    try {
      const result = aliCloudConfigManager.loadConfig()
      if (result.success && result.config) {
        this.config = result.config
        log.info('[阿里云语音] 从配置文件加载配置成功')
        return true
      } else {
        log.error(`[阿里云语音] 配置文件加载失败: ${result.error}`)
        return false
      }
    } catch (error: any) {
      log.error('[阿里云语音] 配置文件加载异常:', error)
      return false
    }
  }

  private async initClient() {
    try {
      if (!this.config) {
        throw new Error('配置信息未加载')
      }

      log.info('[阿里云语音] 开始导入SDK模块...')

      // 尝试多种导入方式来兼容不同的模块系统
      let Dyvmsapi, OpenApiConfig
      
      try {
        // 方法1: 使用动态导入
        log.info('[阿里云语音] 尝试动态导入 dyvmsapi20170525...')
        const dyvmsapiModule = await import('@alicloud/dyvmsapi20170525')
        log.info('[阿里云语音] dyvmsapi 模块结构:', Object.keys(dyvmsapiModule))
        
        // 尝试不同的访问方式
        Dyvmsapi = (dyvmsapiModule as any).default?.default || (dyvmsapiModule as any).default || dyvmsapiModule
        log.info('[阿里云语音] dyvmsapi20170525 模块导入成功')
      } catch (err) {
        log.error('[阿里云语音] 动态导入失败，尝试 require...', err)
        
        try {
          // 方法2: 降级到 require (在某些情况下仍然有效)
          const dyvmsapiModule = require('@alicloud/dyvmsapi20170525')
          Dyvmsapi = dyvmsapiModule.default || dyvmsapiModule
          log.info('[阿里云语音] require 导入成功')
        } catch (requireErr) {
          log.error('[阿里云语音] require 也失败了:', requireErr)
          throw new Error('无法导入 @alicloud/dyvmsapi20170525 依赖')
        }
      }

      try {
        log.info('[阿里云语音] 尝试导入 openapi-client...')
        const openapiModule = await import('@alicloud/openapi-client')
        log.info('[阿里云语音] openapi 模块结构:', Object.keys(openapiModule))
        
        // 获取Config类
        OpenApiConfig = (openapiModule as any).Config || (openapiModule as any).default?.Config || (openapiModule as any).default
        log.info('[阿里云语音] openapi-client 模块导入成功')
      } catch (err) {
        log.error('[阿里云语音] 动态导入 openapi-client 失败，尝试 require...', err)
        
        try {
          const openapiModule = require('@alicloud/openapi-client')
          OpenApiConfig = openapiModule.Config || openapiModule.default?.Config || openapiModule
          log.info('[阿里云语音] openapi-client require 导入成功')
        } catch (requireErr) {
          log.error('[阿里云语音] openapi-client require 也失败了:', requireErr)
          throw new Error('无法导入 @alicloud/openapi-client 依赖')
        }
      }

      log.info('[阿里云语音] 创建OpenApi配置...')
      const config = new OpenApiConfig({
        accessKeyId: this.config.accessKeyId,
        accessKeySecret: this.config.accessKeySecret,
        endpoint: this.config.endpoint || 'dyvmsapi.aliyuncs.com'
      })
      log.info(`[阿里云语音] OpenApi配置创建成功，endpoint: ${config.endpoint}`)
      
      log.info('[阿里云语音] 创建Dyvmsapi客户端...')
      log.info('[阿里云语音] Dyvmsapi类型:', typeof Dyvmsapi)
      this.client = new Dyvmsapi(config)
      this.clientInitialized = true
      
      log.info('[阿里云语音] SDK 初始化成功')
    } catch (error: any) {
      log.error('[阿里云语音] SDK 初始化失败:', error)
      this.clientInitialized = false
      throw new Error(`阿里云语音SDK初始化失败: ${error.message}`)
    }
  }

  /**
   * 确保客户端已初始化
   */
  private async ensureClientInitialized(): Promise<void> {
    if (!this.clientInitialized && this.config) {
      await this.initClient()
    }
  }

  /**
   * 发送语音验证码
   * @param params 语音验证码参数
   */
  async sendVoiceCaptcha(params: VoiceCallParams): Promise<VoiceCallResult> {
    try {
      log.info(`[阿里云语音] 开始发送语音验证码到 ${params.phoneNumber}`)
      
      // 确保客户端已初始化
      await this.ensureClientInitialized()
      
      if (!this.client) {
        throw new Error('阿里云语音客户端未初始化')
      }

      const request = {
        calledNumber: params.phoneNumber,
        ttsCode: params.ttsCode,
        calledShowNumber: params.calledShowNumber || this.config?.calledShowNumber || '4001112222',
        playTimes: params.playTimes || this.config?.defaultPlayTimes || 3,
      }

      const response = await this.client.singleCallByTts(request)
      
      if (response.statusCode === 200 && response.body) {
        const body = response.body
        
        if (body.code === 'OK') {
          log.info(`[阿里云语音] 语音验证码发送成功，CallId: ${body.callId}`)
          return {
            success: true,
            callId: body.callId,
            requestId: body.requestId,
            code: body.code,
            message: body.message
          }
        } else {
          log.error(`[阿里云语音] 发送失败，错误码: ${body.code}, 消息: ${body.message}`)
          return {
            success: false,
            code: body.code,
            message: body.message,
            error: `API调用失败: ${body.message}`
          }
        }
      } else {
        log.error(`[阿里云语音] HTTP请求失败，状态码: ${response.statusCode}`)
        return {
          success: false,
          error: `HTTP请求失败，状态码: ${response.statusCode}`
        }
      }
    } catch (error: any) {
      log.error('[阿里云语音] 发送语音验证码异常:', error)
      return {
        success: false,
        error: error.message || '发送失败'
      }
    }
  }

  /**
   * 查询语音通话详情
   * @param callId 通话ID
   */
  async queryCallDetail(callId: string) {
    try {
      log.info(`[阿里云语音] 查询通话详情，CallId: ${callId}`)
      
      // 确保客户端已初始化
      await this.ensureClientInitialized()
      
      if (!this.client) {
        throw new Error('阿里云语音客户端未初始化')
      }

      const request = {
        callId: callId
      }

      const response = await this.client.queryCallDetailByCallId(request)
      
      if (response.statusCode === 200 && response.body) {
        log.info(`[阿里云语音] 查询通话详情成功`)
        return {
          success: true,
          data: response.body
        }
      } else {
        log.error(`[阿里云语音] 查询通话详情失败，状态码: ${response.statusCode}`)
        return {
          success: false,
          error: `查询失败，状态码: ${response.statusCode}`
        }
      }
    } catch (error: any) {
      log.error('[阿里云语音] 查询通话详情异常:', error)
      return {
        success: false,
        error: error.message || '查询失败'
      }
    }
  }

  /**
   * 测试连接
   */
  async testConnection(): Promise<VoiceCallResult> {
    try {
      // 确保客户端已初始化
      await this.ensureClientInitialized()
      
      if (!this.client) {
        return {
          success: false,
          error: '客户端未初始化'
        }
      }

      // 使用一个无效的号码测试API连通性（不会真实拨打）
      const testRequest = {
        calledNumber: '00000000000',
        ttsCode: '您正在尝试变更${product}重要信息，验证码${code}，请妥善保管账户信息。'
      }

      try {
        await this.client.singleCallByTts(testRequest)
      } catch (error: any) {
        // 预期会失败，但能确认API连通性
        if (error.message && error.message.includes('InvalidPhoneNumber')) {
          return {
            success: true,
            message: 'API连接正常'
          }
        }
      }

      return {
        success: true,
        message: 'API连接测试完成'
      }
    } catch (error: any) {
      return {
        success: false,
        error: error.message || '连接测试失败'
      }
    }
  }

  /**
   * 更新配置
   */
  async updateConfig(config: AliCloudVoiceConfig) {
    this.config = config
    this.clientInitialized = false
    await this.initClient()
  }

  /**
   * 重新加载配置文件
   */
  async reloadConfigFromFile(): Promise<{ success: boolean; error?: string }> {
    try {
      const result = aliCloudConfigManager.reloadConfig()
      if (result.success && result.config) {
        this.config = result.config
        this.clientInitialized = false
        await this.initClient()
        log.info('[阿里云语音] 配置文件重新加载成功')
        return { success: true }
      } else {
        log.error(`[阿里云语音] 配置文件重新加载失败: ${result.error}`)
        return { success: false, error: result.error }
      }
    } catch (error: any) {
      log.error('[阿里云语音] 配置文件重新加载异常:', error)
      return { success: false, error: error.message }
    }
  }

  /**
   * 获取当前配置状态
   */
  getConfigStatus(): { isConfigured: boolean; source: 'file' | 'manual' | 'none'; error?: string } {
    if (!this.config) {
      return { isConfigured: false, source: 'none', error: '未配置' }
    }
    
    // 简单判断是否来自配置文件（配置文件通常包含更多字段）
    const isFromFile = !!(this.config.calledShowNumber || this.config.defaultPlayTimes || this.config.templates)
    
    return {
      isConfigured: true,
      source: isFromFile ? 'file' : 'manual'
    }
  }

  /**
   * 获取叫醒消息模板
   */
  getWakeupTemplate(): string {
    return this.config?.templates?.wakeup || aliCloudConfigManager.getWakeupTemplate()
  }

  /**
   * 获取测试消息模板
   */
  getTestTemplate(): string {
    return this.config?.templates?.test || aliCloudConfigManager.getTestTemplate()
  }
}

// 全局实例（单例）
let aliCloudVoiceService: AliCloudVoiceService | null = null

export function getAliCloudVoiceService(): AliCloudVoiceService | null {
  return aliCloudVoiceService
}

export function initAliCloudVoiceService(config?: AliCloudVoiceConfig): AliCloudVoiceService {
  try {
    aliCloudVoiceService = new AliCloudVoiceService(config)
    return aliCloudVoiceService
  } catch (error) {
    log.error('[阿里云语音] 服务初始化失败:', error)
    throw error
  }
}

/**
 * 从配置文件初始化阿里云语音服务
 */
export function initAliCloudVoiceServiceFromConfig(): { success: boolean; error?: string; service?: AliCloudVoiceService } {
  try {
    // 首先验证配置文件
    const configResult = aliCloudConfigManager.validateConfig()
    if (!configResult.success) {
      return {
        success: false,
        error: configResult.error
      }
    }

    // 初始化服务
    const service = new AliCloudVoiceService()
    if (service.getConfigStatus().isConfigured) {
      aliCloudVoiceService = service
      log.info('[阿里云语音] 从配置文件初始化服务成功')
      return {
        success: true,
        service: service
      }
    } else {
      return {
        success: false,
        error: '配置文件加载失败'
      }
    }
  } catch (error: any) {
    log.error('[阿里云语音] 从配置文件初始化服务失败:', error)
    return {
      success: false,
      error: error.message || '初始化失败'
    }
  }
}

export function destroyAliCloudVoiceService() {
  aliCloudVoiceService = null
}
